<template>
    <div 
        class="chart-box"
        ref="chartRef"
        :option="option"
        >
    </div>
</template>
<script lang="ts" setup>
//引入echarts模块
import { ECharts, init } from 'echarts';

//父组件传值
const props = defineProps({
	chartObject: {
		type: Object,
		default: () => {
			return {
                name: '',
				legend: [],
                legendShow: false,
				data: []
			};
		}
	}
})
//图表ref
const chartRef = ref<HTMLDivElement>();
let myChart: ECharts;
let timer: any;
let option = reactive({});

//初始化options
const initOption = () => {
	option = {
        tooltip: {
            show: false,
            trigger: 'item',
            formatter: "{a} <br/>{b}占比: {d}%"
        },
        legend: {
            show: props.chartObject.legendShow,
            data: props.chartObject.legend,
            top: 'bottom',
            left: 'center',
            icon: 'rect'
        },
        color: ['#0B4ED1','#E07EF9'],
        series: [
            {
                name: props.chartObject.name,
                type: 'pie',
                radius: ['50%', '60%'],
                avoidLabelOverlap: false,
                padAngle: 2,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 22,
                        fontWeight: 'bold',
                        lineHeight: 14,
                        formatter: [
                            '{d}%',
                            '{b|{b}{a}占比}'
                        ].join('\n\n'),
                        rich: {
                            b: {
                                color: '#b1b3b8',
                                fontSize: 10
                            }
                        }
                    }
                },
                labelLine: {
                    show: false
                },
                data: props.chartObject.data
            }
        ]
	}
}
//初始化echarts
const initChart = ():void => {
    if(myChart !== undefined) {
        myChart.dispose();
    }
    initOption();
    myChart = init(chartRef.value as HTMLDivElement);
    //渲染echarts
    myChart?.setOption(option, true);
}

//重新渲染echarts
const resizeChart = ():void => {
    timer = setTimeout(() => {
        if(myChart !== undefined) {
            myChart.resize();
        }
    }, 500);
}

//初始化
const initPage = ():void => {
    initChart();
    window.addEventListener('resize', resizeChart);
}

//销毁
const destroyPage = ():void => {
    window.removeEventListener('resize', resizeChart);
    timer && clearTimeout(timer);
}

onMounted(() => {
    initPage();
});

onBeforeMount(() => {
    destroyPage();
})

watch(
    props.chartObject,
    () => {
        initChart();
    },
    {
        deep: true
    }
)

</script>
<style scoped>
.chart-box {
    width: 100%;
    height: 100%;
}
</style>